let logger = require('log4js').getLogger("default");
const User = require('../../../models/user/userModel.js')
const findUserByPage = async function (query = {}) {
    return new Promise((resolve, reject) => {
        const { page, size, keywords } = query
        let searchQuery = {
            $and: [{ is_delete: false }]
        }
        if (keywords) {
            searchQuery.$or = [{ user_name: { $regex: keywords } }, { nick_name: { $regex: keywords } }]
        }
        User.aggregate([{
            $match: searchQuery
        },
        { $skip: (page - 1) * size },
        { $limit: parseInt(size) || 20 },
        {
            $lookup: {
                from: 'configs',
                localField: 'user_code',
                foreignField: 'user_code',
                as: 'config'
            }
        }, {
            $unwind: {
                path: '$config',
                preserveNullAndEmptyArrays: true,
            }
        },
        {
            $project: { _id: 0, user_name: 1, mobile: 1, create_time: 1, nick_name: 1, user_code: 1, 'config.theme': 1 }
        }
        ]).sort({ 'create_time': 1 }).exec(async (err, doc) => {
            if (err) {
                logger.error(err)
                reject(err)
            } else {
                let data = {
                    list: doc,
                    meta: {
                        total: await User.countDocuments(searchQuery),
                        page,
                        size
                    }
                }
                resolve(data)
            }
        })
    });
};

module.exports = { findUserByPage }